package com.kuanter.kuanterauto.main;

import java.io.Serializable;
import java.lang.reflect.Constructor;
import java.util.ArrayList;
import java.util.List;

import android.annotation.SuppressLint;
import android.app.ActivityGroup;
import android.app.LocalActivityManager;
import android.app.PendingIntent;
import android.app.PendingIntent.CanceledException;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.PowerManager.WakeLock;
import android.provider.Settings;
import android.provider.Settings.Secure;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.kuanter.kuanterauto.R;
import com.kuanter.kuanterauto.activity.LoginActivity;
import com.kuanter.kuanterauto.activity.MerchantTurnActivity1;
import com.kuanter.kuanterauto.activity.ServicesActivity;
import com.kuanter.kuanterauto.activity.SettingActivity;
import com.kuanter.kuanterauto.activity.VipCenterActivity;
import com.kuanter.kuanterauto.baseui.BaseActivityGroup;
import com.kuanter.kuanterauto.baseui.ProApplication;
import com.kuanter.kuanterauto.constants.MainConstants;
import com.kuanter.kuanterauto.dataservices.PushServices;
import com.kuanter.kuanterauto.entity.MapResult;
import com.kuanter.kuanterauto.entity.MessageInfo;
import com.kuanter.kuanterauto.entity.MessageInfoList;
import com.kuanter.kuanterauto.net.HttpTask;
import com.kuanter.kuanterauto.param.ActivityHolder;
import com.kuanter.kuanterauto.utils.DataLoader;
import com.kuanter.kuanterauto.utils.SharePrefenceUtil;
import com.umeng.analytics.MobclickAgent;

/**
 * 主界面
 * 
 * @author soup
 * 
 */
@SuppressLint("HandlerLeak")
public class HomeActivityGroup extends BaseActivityGroup {


	public static HomeActivityGroup homeActivityGroup = null;

	public static LinearLayout layBody;// װ 装载sub Activity的容器

	private static Window subActivity;
	MapResult mapR = null;

	public static String backAction = "";

//	Bundle carinfos_bundle = null;// 数据
	Bundle msgBundle=null;

	private DataReceiver dataReceiver = null;

	// int select_id=0;

	public static List<Integer> select_id = null;// 记录点击子项的id容器  

	// android:theme="@style/ContentOverlay"

	WakeLock wakeLock = null;

	long flag = -1;// 退出开关
	
	
	DataLoader dataLoader=null;
	
	
	String versionInfo="";
	
	ImageView kuanter_vip;
	LinearLayout lin_vip;
	
	ImageView kuanter_sercice;
	LinearLayout lin_service;
	
	ImageView kuanter_more;
	LinearLayout lin_more;
	
	Handler handler=new Handler(){
		public void handleMessage(android.os.Message msg) {
			switch(msg.what){
			case HttpTask.RESULT_OK:
//				Bundle bundle = msg.getData();
//				String json = bundle.getString("result");
				String json = (String) msg.obj;
				System.out.println(json + "");
				MessageInfoList msgList=new MessageInfoList(json);
				List<MessageInfo> messageInfos=msgList.getMessageInfos();
				if(messageInfos!=null&&messageInfos.size()>0){
//					adapter.showReaddian();
				}
				msgBundle=new Bundle();
				msgBundle.putSerializable(MessageInfo.TAG, (Serializable)messageInfos);
			case HttpTask.RESULT_ERROR:
				break;
			}
		}
	};

	
	
	ProApplication application;
	static ImageView badge;
	public static final int show = 0;
	public static final int disapper = 1;
	ShowMessageIcon showIconReceive;
	public static String show_action = "com.show.message";
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.home_group);
		application = (ProApplication) getApplication();
		homeActivityGroup = this;
		
		showIconReceive = new ShowMessageIcon();
		IntentFilter filter = new IntentFilter(show_action);
		registerReceiver(showIconReceive, filter);
		
		badge = (ImageView) findViewById(R.id.badge);
		badge.setVisibility(View.INVISIBLE);
		
		mapR = MapResult.getMapResults();

//		mBMapMan = new BMapManager(this);
//		mBMapMan.init("755CDC09D6ACCAD8274A01D02576948F7904B7A1",
//				new MyGeneralListener());
		select_id = new ArrayList<Integer>();	
		dataLoader=new DataLoader(this);
		
//		carinfos_bundle = new Bundle();
		if (getIntent().getExtras() != null) {
//			carinfos_bundle.putSerializable(CardInfoList.TAG, getIntent()
//					.getSerializableExtra(CardInfoList.TAG));
//			carinfos_bundle.putSerializable(ConsumptionList.TAG, getIntent()
//					.getSerializableExtra(ConsumptionList.TAG));
//			carinfos_bundle.putSerializable(VehicleInfoList.TAG, getIntent()
//					.getSerializableExtra(VehicleInfoList.TAG));
			msgBundle=getIntent().getExtras();
		}else{
			//TODO myupdate
//			System.out.println("msg_home");
//			List<NameValuePair> params=new ArrayList<NameValuePair>();
//			params.add(new BasicNameValuePair("deviceToken", MainActivity.Token));
//			dataLoader.DisplayData(MainConstants.HOST+"query_unRead_message", params, handler, "", false);
		}

		
		
		

		register_Receiver();

		initView();
		initListener();
		getData(ProApplication.KUANTER_FW);  //默认打开服务项
		
//		getVersion();
//		checkVersion();
	}

	@Override
	protected void onResume() {
		/*if(PushServices.getmessageInfos() != null && PushServices.getmessageInfos().size() > 0) {
			badge.setVisibility(View.VISIBLE);
		}*/
		if(PushServices.unReadMessage > 0) {
			badge.setVisibility(View.VISIBLE);
		}
		MobclickAgent.onResume(this);
		super.onResume();
	}

	@Override
	protected void onPause() {
		MobclickAgent.onPause(this);
		super.onPause();
	}

	@Override
	protected void onStop() {
		super.onStop();
	}

	@Override
	protected void onRestart() {
		// TODO Auto-generated method stub
		super.onRestart();
		System.out.println(backAction);
		if (!backAction.equals("")) {
			if (backAction.equals(MainConstants.HY_ACTION)) {
				getData(ProApplication.KUANTER_HY);
			} else if (backAction.equals(MainConstants.BACK_ACTION)) {
				getData(select_id.get(select_id.size() - 2));	
				select_id.remove(select_id.size() - 2);  
			} else if (backAction.equals(MainConstants.SZ_ACTION)) {
				getData(ProApplication.KUANTER_GD);
			}
		} else {
			getData(ProApplication.KUANTER_FW);// 默认打开第1页
//			kuanter_sercice.setSelected(true);
//			kuanter_vip.setSelected(false);
//			kuanter_more.setSelected(false);
		}
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (dataReceiver != null) {
			unregisterReceiver(dataReceiver);
			dataReceiver = null;
		}
		
		if(showIconReceive != null) {
			unregisterReceiver(showIconReceive);
		}

		if (select_id != null) {
			select_id.clear();
			select_id = null;
		}

		/*if (mBMapMan != null) {
			mBMapMan.destroy();
			mBMapMan = null;
		}*/

		mapR.clearCache();

		MainActivity.ID = 0;
		
//		System.exit(0);
		if(isGPSEnable()) {
			closeGps();
//			toggleGps(this);
//			close();
		}

	}
	
	public void close() {
		try {
			Class clz = Class.forName("com.android.settings.widget.SettingsAppWidgetProvider");
			Constructor[] con = clz.getDeclaredConstructors();
			int i = 0;
			i++;
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}
	
	//关闭gps
	public void closeGps() {
        Intent GPSIntent = new Intent();
        GPSIntent.setClassName("com.android.settings",
                "com.android.settings.widget.SettingsAppWidgetProvider");
        GPSIntent.addCategory("android.intent.category.ALTERNATIVE");
        GPSIntent.setData(Uri.parse("custom:3"));
        try {
            PendingIntent.getBroadcast(this, 0, GPSIntent, 0).send();
        } catch (CanceledException e) {
            e.printStackTrace();
        }    
	}
	
	//判断gps是否开启
	private boolean isGPSEnable() {
		/* 用Setting.System来读取也可以，只是这是更旧的用法
		String str = Settings.System.getString(getContentResolver(),
				Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
		*/
		String str = Settings.Secure.getString(getContentResolver(),
				Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
		Log.v("GPS", str);
		if (str != null) {
			return str.contains("gps");
		}
		else{
			return false;
		}
		
	}
	
	 private void toggleGps(Context context) {
	        ContentResolver resolver = context.getContentResolver();
	        Settings.Secure.setLocationProviderEnabled(resolver, LocationManager.GPS_PROVIDER,
	          false);
	    }
	
	public boolean isGpsOpen() {
		return Secure.isLocationProviderEnabled(getContentResolver(), Secure.LOCATION_PROVIDERS_ALLOWED);
	}


//	FrameLayout mFrameTv;
//	ImageView iv_off;
	private void initView() {
		layBody = (LinearLayout) findViewById(R.id.layBody);
//		gvNavigationBar = (GridView) this.findViewById(R.id.gvNavigationBar); // //
//																				// 底部bar
//		gvNavigationBar.setNumColumns(topbar_image_array.length);// 设置每行列数
//		gvNavigationBar.setGravity(Gravity.BOTTOM);// 位置居中
//		gvNavigationBar.setVerticalSpacing(0);// 垂直间隔
//		gvNavigationBar.setHorizontalSpacing(0);
		
		kuanter_vip = (ImageView) findViewById(R.id.kuanter_vip);
		lin_vip = (LinearLayout) findViewById(R.id.lin_vip);
		
		kuanter_sercice = (ImageView) findViewById(R.id.kuanter_sercice);
		lin_service = (LinearLayout) findViewById(R.id.lin_service);
		
		kuanter_sercice.setSelected(true);
		lin_service.setSelected(true);
		
		kuanter_more = (ImageView) findViewById(R.id.kuanter_more);
		lin_more = (LinearLayout) findViewById(R.id.lin_more);
		
		/*//退出动画
		mFrameTv = (FrameLayout) findViewById(R.id.fl_off);
		iv_off = (ImageView) findViewById(R.id.iv_off);*/
	}


	public void initListener() {
		// 项目点击事件
//		gvNavigationBar.setOnItemClickListener(new gridClickListener());
		lin_vip.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				getData(ProApplication.KUANTER_HY);
			}
		});
		
		lin_service.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				getData(ProApplication.KUANTER_FW);
			}
		});
		
		lin_more.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				getData(ProApplication.KUANTER_GD);
			}
		});
	}


	/**
	 * 根据ID加载指定的Activity 数据
	 * 
	 * @param id
	 *            GridView选中项的序号
	 */
	private void getData(int index) {
		switch (index) {
		case ProApplication.KUANTER_HY:// 会员
			switchActivity(ProApplication.KUANTER_HY);
			break;
		case ProApplication.KUANTER_FW:// 服务
			switchActivity(ProApplication.KUANTER_FW);
			
			break;
		case ProApplication.KUANTER_GD:// 设置
			switchActivity(ProApplication.KUANTER_GD);
			break;
		}
	}

	/**
	 * 根据ID打开指定的Activity
	 * 
	 * @param id
	 *            GridView选中项的序号
	 */
	private void switchActivity(int id) {
		// System.gc();
//		adapter.setFocus(id);

		select_id.add(id);  	
		switch (id) {
		case ProApplication.KUANTER_HY:// 会员
			backAction = MainConstants.HY_ACTION;  
			if(SharePrefenceUtil.checkLogin(HomeActivityGroup.this)){
//				startMyActivity(VipCenterActivity.class);
				myStartActivity(VipCenterActivity.class, null);
			}else {
//				startMyActivity(LoginActivity.class);
				qStartActivity(LoginActivity.class, null,MainConstants.HY_ACTION);
				startActivity_anim(7);
			}
			
			/*System.out.println(MainActivity.ID);
			backAction = MainConstants.HY_ACTION;
			if (MainActivity.ID == 0) {
				qStartActivity(UserLoginActivity.class, null,
						MainConstants.HY_ACTION);
				startActivity_anim(7);
			} else {
//				if (carinfos_bundle != null) {
//					myStartActivity(HuiYuanActivity.class, carinfos_bundle);
//				} else {
					myStartActivity(VipCenterActivity.class, null);
//				}
			}*/
			kuanter_vip.setSelected(true);
			lin_vip.setSelected(true);
			kuanter_sercice.setSelected(false);
			lin_service.setSelected(false);
			kuanter_more.setSelected(false);
			lin_more.setSelected(false);
			break;
		case ProApplication.KUANTER_FW:// 服务
			backAction = MainConstants.XX_ACTION;
			if(msgBundle!=null){
				System.out.println("not null");
				myStartActivity(ServicesActivity.class, msgBundle);
			}else{
				System.out.println("null");
			    myStartActivity(ServicesActivity.class, null);
			}
//			adapter.goneReaddian();
			SharedPreferences sp = getSharedPreferences("push", MODE_PRIVATE);
			SharedPreferences.Editor editor = sp.edit();
			editor.putBoolean("push", false);
			editor.commit();
			kuanter_sercice.setSelected(true);
			lin_service.setSelected(true);
			kuanter_vip.setSelected(false);
			lin_vip.setSelected(false);
			kuanter_more.setSelected(false);
			lin_more.setSelected(false);
			break;
		case ProApplication.KUANTER_GD:// 更多
			backAction = MainConstants.SZ_ACTION;
			myStartActivity(SettingActivity.class, null);
			kuanter_more.setSelected(true);
			lin_more.setSelected(true);
			kuanter_vip.setSelected(false);
			lin_vip.setSelected(false);
			kuanter_sercice.setSelected(false);
			lin_service.setSelected(false);
			break;
		}
	}

	/**
	 * 自定义跳转，可传参数
	 * 
	 * @param act
	 * @param bundle
	 */
	public static void myStartActivity(Class act, Bundle bundle) {
		Intent intent = null;
		layBody.removeAllViews();
		ActivityGroup ag = HomeActivityGroup.homeActivityGroup;
		intent = new Intent(ag, act);

		// if(!action.equals(""))
		// intent.setAction(action);

		ActivityHolder holder = new ActivityHolder();
		holder.setActClass(act);
		if (bundle != null) {

			holder.setBundle(bundle);
		}
		ProApplication.actStack.push(holder);
		if (bundle != null) {
			intent.putExtras(bundle);
		}
		intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		// Activity 转为 View
		LocalActivityManager ap = ag.getLocalActivityManager();
		subActivity = ag.getLocalActivityManager().startActivity("subActivity",
				intent);
		// 容器添加View
		layBody.addView(subActivity.getDecorView(), LayoutParams.FILL_PARENT,
				LayoutParams.FILL_PARENT);
	}

	@Override
	public void onClick(View v) {

	}
	

	// <uses-permission
	// android:name="android.permission.DISABLE_KEYGUARD"></uses-permission>
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {

		switch (keyCode) {
		case KeyEvent.KEYCODE_BACK:
			ExitApp();
			break;
		}
		return true; 
	}

	
	public void ExitApp() {
		if (flag == -1 || System.currentTimeMillis() - flag > 2000) {
			showToast("再点击一次退出");
			flag = System.currentTimeMillis();

		} else if (System.currentTimeMillis() - flag < 2000) {
//			startServices();  
			
			/*mFrameTv.setVisibility(0);
			iv_off.setVisibility(0);
			Animation anim = AnimationUtils.loadAnimation(
					HomeActivityGroup.this, R.anim.tv_off);
			anim.setAnimationListener(new tvOffAnimListener());
			iv_off.startAnimation(anim);*/
			finish();
			System.exit(0);
		}
		
	}
	
	private void startServices(){
		Intent i = new Intent(this, PushServices.class);
		startService(i);
	}

	// @Override
	// public void onAttachedToWindow() {
	// this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD);
	// super.onAttachedToWindow();
	// }

	/**
	 * 注册广播
	 */
	private void register_Receiver() {
		IntentFilter filter = new IntentFilter();
		filter.addAction(MainConstants.Data_ACTION);
		dataReceiver = new DataReceiver();
		registerReceiver(dataReceiver, filter);
	}

	class DataReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			if (intent.getAction().equals(MainConstants.Data_ACTION)) {
				
				if (!backAction.equals("")) {
					System.out.println(backAction);
					if (backAction.equals(MainConstants.HY_ACTION)) {// 打开会员
						// carinfos_bundle = null;
						// carinfos_bundle = intent.getExtras();
						// carinfos = (List<CardInfo>)
						// bundle.getSerializable(CardInfoList.TAG);
						getData(ProApplication.KUANTER_HY);
					} else if (backAction.equals(MainConstants.SZ_ACTION)) {// 打开更多
						// carinfos_bundle = null;
						// carinfos_bundle = intent.getExtras();
						getData(ProApplication.KUANTER_GD);
					} else if (backAction.equals(intent
							.getStringExtra("action"))) {// 默认打开第0页
						getData(ProApplication.KUANTER_FW);// 默认打开第1页
					}
				} else {
					getData(ProApplication.KUANTER_FW);// 默认打开第1页
				}
			}
		}

	}
	
	class tvOffAnimListener implements AnimationListener {

		@Override
		public void onAnimationEnd(Animation animation) {
			// TODO Auto-generated method stub
			finish();
		}

		@Override
		public void onAnimationRepeat(Animation animation) {
			// TODO Auto-generated method stub

		}

		@Override
		public void onAnimationStart(Animation animation) {
			// TODO Auto-generated method stub

		}

	}
	
	class ShowMessageIcon extends BroadcastReceiver {
		@Override
		public void onReceive(Context context, Intent intent) {
			int status = intent.getIntExtra("status", -1);
			if(status == show) {
				if(badge != null) {
					badge.setVisibility(View.VISIBLE);
				}
			} else if(status == disapper) {
				if(badge != null) {
					badge.setVisibility(View.INVISIBLE);
				}
			}
		}
		
	}
	

}

// 常用事件监听，用来处理通常的网络错误，授权验证错误等
/*class MyGeneralListener implements MKGeneralListener {

	@Override
	public void onGetNetworkState(int iError) {
		if (iError == MKEvent.ERROR_NETWORK_CONNECT) {
			System.out.println("您的网络出错啦！");
		} else if (iError == MKEvent.ERROR_NETWORK_DATA) {
			// Toast.makeText(DemoApplication.getInstance().getApplicationContext(),
			// "输入正确的检索条件！",
			// Toast.LENGTH_LONG).show();
			System.out.println("您的网络出错啦！");
		}
		// ...
	}

	@Override
	public void onGetPermissionState(int iError) {
		if (iError == MKEvent.ERROR_PERMISSION_DENIED) {
			// 授权Key错误：
			// Toast.makeText(DemoApplication.getInstance().getApplicationContext(),
			// "请在 DemoApplication.java文件输入正确的授权Key！",
			// Toast.LENGTH_LONG).show();
			// DemoApplication.getInstance().m_bKeyRight = false;
			System.out.println("授权Key错误：");
		}
	}
}*/
